package com.maserb.monitor.service.jwQuestion.impl;

import com.maserb.monitor.common.CreateTimeUtils;
import com.maserb.monitor.common.JpushClientUtil;
import com.maserb.monitor.entity.JwEducationInfoEntity;
import com.maserb.monitor.entity.JwRegistrationEntity;
import com.maserb.monitor.entity.jwQuestion.*;
import com.maserb.monitor.repository.JwQuestion.JwQuestionRepository;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.common.JwRegistrationService;
import com.maserb.monitor.service.jwQuestion.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class JwQuestionServiceImpl extends JpaSpecificationServiceImpl<JwQuestionRepository,
        JwQuestionRepository, JwQuestionEntity, String>
        implements JwQuestionService {


    @Autowired
    JwRegistrationService registrationService;

    @Autowired
    JwQuestionUserService questionUserService;

    @Autowired
    JwQuestionItemService questionItemService;

    @Autowired
    JwQuestionOptionService questionOptionService;

    @Override
    public Page<JwQuestionEntity> findAll(Pageable pageable,String schoolId, String name,String status ,String isTop) {
        return this.findAll(new Specification<JwQuestionEntity>() {
            @Override
            public Predicate toPredicate(Root<JwQuestionEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> pathName = root.get("name");
                Path<String> pathStatus = root.get("status");
                Path<String> pathIsTop = root.get("isTop");
                Path<String> pathIsDel = root.get("isDel");
                Path<String> pathSchoolId = root.get("schoolId");
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmptyOrWhitespace(name)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.like(pathName, "%"+name+"%")));
                }
                if (!StringUtils.isEmptyOrWhitespace(status)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathStatus, status)));
                }
                if (!StringUtils.isEmptyOrWhitespace(isTop)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathIsTop, isTop)));
                }
                if (!StringUtils.isEmptyOrWhitespace(schoolId)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathSchoolId, schoolId)));
                }
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathIsDel,"0")));
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    @Override
    public Page<JwQuestionEntity> findAll(Pageable pageable,String schoolId) {
        return this.findAll(new Specification<JwQuestionEntity>() {
            @Override
            public Predicate toPredicate(Root<JwQuestionEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> pathIsDel = root.get("isDel");
                Path<String> pathStatus = root.get("status");
                Path<String> pathSchoolId = root.get("schoolId");
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmptyOrWhitespace(schoolId)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathSchoolId, schoolId)));
                }
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathIsDel,"0")));
                //只显示已发布的问卷
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathStatus,"1")));
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    @Override
    public List<JwQuestionEntity> findAll() {
        return this.findAll(new Specification<JwQuestionEntity>() {
            @Override
            public Predicate toPredicate(Root<JwQuestionEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<String> pathIsDel = root.get("isDel");
                Path<String> pathStatus = root.get("status");
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathIsDel,"0")));
                //只显示已发布的问卷
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathStatus,"1")));
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        });
    }

    //发布测评，并推送给3天内使用过app的用户
    @Override
    public void doRelease(String id) {
        JwQuestionEntity entity = this.findOne(id);
        //判断是否已发布或者已完结
        if("1".equals(entity.getStatus()) || "2".equals(entity.getStatus())){
            entity.setStatus("1");
            this.save(entity);
            return;
        }
        entity.setStatus("1");
        this.save(entity);
    }

    //结束测评（判断是否中奖）
    @Override
    public void doDisabled(String id) {
        JwQuestionEntity entity = this.findOne(id);
        entity.setStatus("2");
        this.save(entity);
    }

    @Override
    public void doTop(String id) {
        JwQuestionEntity entity = this.findOne(id);
        Integer favorite = find();
        entity.setFavorites(favorite+1);
        entity.setIsTop("1");
        this.save(entity);
    }

    @Override
    public void cancelTop(String id) {
        JwQuestionEntity entity = this.findOne(id);
        entity.setFavorites(0);
        entity.setIsTop("0");
        this.save(entity);
    }

    @Override
    public void dodelete(String id) {
        JwQuestionEntity entity = this.findOne(id);
        entity.setIsDel("1");
        this.save(entity);
    }

    @Override
    public void saveImport(String title, List<JwQuestionItemEntity> list,String schoolId) {
        JwQuestionEntity questionEntity = new JwQuestionEntity();
        questionEntity.setName(title);
        //默认为问卷调查
        questionEntity.setCreateTime(CreateTimeUtils.getCreateTime());
        questionEntity.setStatus("0");
        questionEntity.setIsDel("0");
        questionEntity.setIsTop("0");
        questionEntity.setFavorites(0);
        questionEntity.setSchoolId(schoolId);
        this.save(questionEntity);
        saveItems(questionEntity,list);
    }

    private void saveItems(JwQuestionEntity questionEntity, List<JwQuestionItemEntity> list){
        for(JwQuestionItemEntity itemEntity:list){
            itemEntity.setParent(questionEntity);
            try {
                questionItemService.save(itemEntity, questionEntity.getId());
            }catch (Exception e){
                e.printStackTrace();
            }
            if(null!=itemEntity.getOptions()&&itemEntity.getOptions().size()>0&&!"3".equals(itemEntity.getType())){
                for(JwQuestionOptionEntity optionEntity:itemEntity.getOptions()){
                    try{
                        questionOptionService.save(optionEntity,itemEntity.getId());
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }
        }

    }

    @Override
    public Integer find() {
        return this.repository.find();
    }


}